package net.guerlab.sdk.dingtalk.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * 请求参数工具类
 *
 * @author guer
 */
@Slf4j
public class RequestParamsUtils {

    private RequestParamsUtils() {

    }

    /**
     * 构造请求地址
     *
     * @param baseUrl
     *         基础地址
     * @param requestParams
     *         请求参数
     * @return 请求地址
     */
    public static String build(String baseUrl, Map<String, String> requestParams) {
        StringBuilder builder = new StringBuilder(baseUrl);

        if (requestParams.isEmpty()) {
            return builder.toString();
        }

        boolean hasQuestionMark = builder.indexOf("?") != -1;

        for (Map.Entry<String, String> entry : requestParams.entrySet()) {
            if (StringUtils.isBlank(entry.getKey())) {
                continue;
            }
            if (hasQuestionMark) {
                builder.append("&");
            } else {
                builder.append("?");
                hasQuestionMark = true;
            }

            builder.append(entry.getKey());
            builder.append("=");
            builder.append(getRequestValue(entry.getValue()));
        }

        return builder.toString();
    }

    /**
     * 获取请求值
     *
     * @param object
     *         数据对象
     * @return 字符串值
     */
    protected static String getRequestValue(Object object) {
        if (object == null) {
            return "";
        }

        try {
            return URLEncoder.encode(object.toString(), StandardCharsets.UTF_8);
        } catch (Exception e) {
            log.debug(e.getMessage(), e);
            return "";
        }
    }
}
